import { MessageStatus } from './../../domain/models/message';
import { ApiDataContext } from './../../domain/apiDataContext';
import { Transaction } from 'tiny-entity2';
import { ServiceManager } from './../../common/serviceFactory/serviceManager';
import * as Koa from 'koa';
import { route, RouteOptionsVerify, UsingLock } from "../../common";
import { MessageService } from '../../service/messageService';
import { Message } from '../../domain/models/message';
import { ServiceException } from '../../common/excpetion';
const msgSvr = ServiceManager.Current.GetService<MessageService>('MessageService');

class MessageController {
    @route(new RouteOptionsVerify('GET', '/api/message'))
    async queryMessages(ctx: Koa.Context, next) {
        const params = ctx.query;
        ctx.response.body = await msgSvr.QueryMessage(params);
        await next();
    }
    @route(new RouteOptionsVerify('GET', '/api/message/:id'))
    async getMessageInfoById(ctx: Koa.Context, next) {
        ctx.response.body = null;
        await next();
    }
    @route(new RouteOptionsVerify('POST', '/api/message'))
    async createMessage(ctx: Koa.Context, next) {
        const msg: Message = ctx.request.body;

        if (!msg.id) {
            throw new ServiceException('未传入Id');
        }

        if (msg.receiverIds && msg.receiverIds.length == 0) {
            msg.receiverIds = null;
        }

        const has = await msgSvr.GetMessageById(msg.id);
        if (has) {
            // 只有任务预警消息一个任务只允许发送一条
            ctx.response.body = has;
        }
        else {
            ctx.response.body = await UsingLock(msg.id, async () => {
                return Transaction(new ApiDataContext(), async ctx => {
                    msg.createTime = Date.now();
                    msg.updateTime = Date.now();
                    msg.status = MessageStatus.UnDo;

                    return msgSvr.CreateMessage(msg, ctx);
                });
            });
        }

        await next();
    }
    @route(new RouteOptionsVerify('PUT', '/api/message'))
    async updateMessage(ctx: Koa.Context, next) {
        ctx.response.body = null;
        await next();
    }
    @route(new RouteOptionsVerify('DELETE', '/api/message'))
    async deleteMessage(ctx: Koa.Context, next) {
        ctx.response.body = null;
        await next();
    }
}